<%-- 
    Document   : journal
    Created on : Dec 5, 2012, 5:20:52 PM
    Author     : Quang Nhat
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Edit Transaction</title>
        <script src="js/xml.js" type="text/javascript"></script>
        <script src="js/table.js" type="text/javascript"></script>
        <script type="text/javascript">
            function initCombo() {
                var dom = getXMLDOM();
                dom.load("Accountant/XML?action=listAccount");
                var xslDom = getXMLDOM();
                xslDom.load("Accountant/XML?action=xslAccountCombo");
                return dom.transformNode(xslDom);
            }
            var comboHTML = initCombo();
            var count = 0;
            var curr = "";
            var xmlContent='${requestScope.xmlContent}';
            var tranId = 0;
            var saveParam = "txtMinDate=" + "${param.txtMinDate}"+"&txtMaxDate=" + "${param.txtMaxDate}"+"&txtText=" + "${param.txtText}";
            function createCombo(id) {
                var dom = getXMLDOM();
                dom.loadXML(comboHTML);
                dom.documentElement.setAttribute("id", id);
                return dom.xml;
            }
            function calcSum() {
                var table = document.getElementById("transactionDetail");
                var debit = 0;
                var credit = 0;
                
                for (var i = 1; i  < table.rows.length - 1; i ++) {
                    var id = table.rows[i].firstChild.firstChild.id.substr(3);
                    debit += Number(document.getElementById("debit" + id).value);
                    credit += Number(document.getElementById("credit" + id).value);
                }
                
                document.getElementById("sumDebit").innerHTML = debit;
                document.getElementById("sumCredit").innerHTML = credit;
                return debit == credit;
            }
            function onDebitChange(id){
                var e = window.event;
                var key = String.fromCharCode(e.keyCode|e.charCode);
                
                var o = document.getElementById("credit" + id);
                if("0123456789".indexOf(key) >=0 || (key=="." && (o.value + curr).indexOf(".") < 0)){
                    o.value = "";
                    if (id == count) {
                        addNewDetail("transactionDetail");
                    }
                    curr += key;
                    return true;
                }
                return false;
            }
            function onCreditChange(id) {
                var e = window.event;
                var key = String.fromCharCode(e.keyCode|e.charCode);
                
                var o = document.getElementById("debit" + id);
                if("0123456789".indexOf(key) >=0 || (key=="." && (o.value + curr).indexOf(".") < 0)){
                    o.value = "";
                    if (id == count) {
                        addNewDetail("transactionDetail");
                    }
                    curr += key;
                    return true;
                }
                return false;
            }
            function onDebitCreditChange() {
                calcSum();
                curr="";
            }
            function removeDetail(id) {
                var table = document.getElementById("transactionDetail");
                if (id < count) {
                    for (var i = 1; i  < table.rows.length - 1; i ++) {
                        if (table.rows[i].firstChild.firstChild.id == "acc" + id) {
                            deleteTableRow("transactionDetail", i);
                            calcSum();
                            return;
                        }
                    }
                }
            }
            function addNewDetail(tableId) {
                var cells = [];
                count++;
                cells[0] = createCombo("acc" + count);
                cells[1] = '<input id="debit'+count+'" type="text" name="" value="" onchange="onDebitCreditChange();" onkeypress="return onDebitChange(\''+count+'\');"/>';
                cells[2] = '<input id="credit'+count+'" type="text" name="" value="" onchange="onDebitCreditChange();" onkeypress="return onCreditChange(\''+count+'\');"/>';
                cells[3] = '<input type="button" value="x" onclick="removeDetail(\'' + count + '\');"/>';
                var table = document.getElementById(tableId);
                insertTableRow(tableId, cells, table.rows.length - 1);
            }
            
            function createXML() {
                var doc = getXMLDOM();
                doc.loadXML("<Transactions></Transactions>");
                
                var txtDate = document.getElementById("txtAddDate").value;
                var parts = txtDate.split("/");
                var date = parts[2] + "-"+ parts[1] + "-"+ parts[0];
                var explanation = document.getElementById("txtAddExplanation").value;
                
                var tran = doc.createElement("Transaction");
                tran.setAttribute("Date", date);
                tran.setAttribute("Id", tranId);
                
                doc.documentElement.appendChild(tran);
                
                var exp = doc.createElement("Explanation");
                exp.appendChild(doc.createTextNode(explanation));
                tran.appendChild(exp);
                
                var table = document.getElementById("transactionDetail");
                for (var i = 1; i  < table.rows.length - 2; i ++) {
                    var id = table.rows[i].firstChild.firstChild.id.substr(3);
                    var detail = doc.createElement("Detail");
                    detail.setAttribute("Id", 0);
                    detail.setAttribute("AccountId", document.getElementById("acc" + id).value);
                    
                    var debit = Number(document.getElementById("debit" + id).value);
                    var credit = Number(document.getElementById("credit" + id).value);
                    
                    detail.setAttribute("Amount", (debit + credit));
                    detail.setAttribute("IsDebit", (debit > 0 ? "true" : "false"));
                    
                    if (debit + credit > 0) {
                        tran.appendChild(detail);
                    }
                }
                return doc;
            }
            function save() {
                var txtDate = document.getElementById("txtAddDate").value;
                var parts = txtDate.split("/");
                if (parts.length != 3) {
                    alert("Invalid Transaction Date.");
                    document.getElementById("txtAddDate").focus();
                    return;
                }
                var date = new Date(parts[2], parts[1] - 1, parts[0]);
                if (date == "Invalid Date") {
                    alert("Invalid Transaction Date.");
                    document.getElementById("txtAddDate").focus();
                    return;
                }
                var explanation = document.getElementById("txtAddExplanation").value;
                if (explanation.trim().length == 0) {
                    alert("Explanation cannot be null or empty.");
                    document.getElementById("txtAddExplanation").focus();
                    return;
                }
                if (!calcSum()) {
                    alert("Total debit and credit must be equal.");
                    return;
                }
                
                var table = document.getElementById("transactionDetail");
                var u = [];
                for (var i = 1; i  < table.rows.length - 2; i ++) {
                    var id = table.rows[i].firstChild.firstChild.id.substr(3);
                    var a = document.getElementById("acc" + id).value;
                    if (u.indexOf(a)>=0) {
                        alert("Duplicate account of row " + (u.indexOf(a) + 1) + " and row " + i + ".");
                        return;
                    }
                    u.push(a);
                }
                var doc = createXML();
                var content = "action=";
                if (tranId == 0) {
                    content += "addTransaction";
                } else {
                    content += "updateTransaction";
                }
                content += "&content=" + doc.xml;
                var result = sendXmlHttpRequest("Accountant/XML", content);
                //if (result == "true") {
                    window.location= "Accountant?action=listTransaction&" + saveParam;
                //} else {
                //    alert(result);
                //}
            }
            function init() {
                document.getElementById("btnCancel").href+="&" + saveParam;
                if (xmlContent == "") {
                    addNewDetail('transactionDetail');
                    var date = new Date();
                    document.getElementById("txtAddDate").value = date.getDate() + "/" + (date.getMonth() + 1) + "/" + (date.getYear() + 1900);
                } else {
                    var doc = getXMLDOM();
                    doc.loadXML(xmlContent);
                    var root = doc.documentElement.childNodes[0];
                    
                    var date = root.getAttribute("Date");
                    var parts = date.split("-");
                    document.getElementById("txtAddDate").value = parts[2] + "/" + parts[1] + "/" + parts[0];
                    
                    tranId = Number(root.getAttribute("Id"));
                    for(var i = 0; i < root.childNodes.length; i++) {
                        var node = root.childNodes[i];
                        if(node.nodeName == "Explanation") {
                            document.getElementById("txtAddExplanation").value = node.firstChild.nodeValue;
                        } else {
                            addNewDetail('transactionDetail');
                            var isDebit = node.getAttribute("IsDebit");
                            var amount = node.getAttribute("Amount");
                            var accountId = node.getAttribute("AccountId");
                            document.getElementById("acc" + count).value = accountId;
                            if (isDebit == "true") {
                                document.getElementById("debit" + count).value = amount;
                            } else {
                                document.getElementById("credit" + count).value = amount;
                            }
                        }
                    }
                    addNewDetail('transactionDetail');
                    calcSum();
                }
            }
        </script>
    </head>
    <body onload="init();">
        <%@include file="/WEB-INF/jspf/Header.jspf" %>
        <c:choose>
            <c:when test="${not empty requestScope.xmlContent}">
                <h1>Edit Transaction</h1>
            </c:when>
            <c:otherwise>
                <h1>Add Transaction</h1>
            </c:otherwise>
        </c:choose>
        <div class="form" style="overflow: hidden;width:650px">
            <div style="width:300px;margin-bottom: 10px;float:left;">
                <div><label >Date: <input id="txtAddDate" type="text" name="txtAddDate" value="" /></label></div>
                <div><label >Explanation: <textarea id="txtAddExplanation" rows="4" cols="20" style="height: 60px; float: right">Explanation Here</textarea> </label></div>
            </div>
            <table border="1" id="transactionDetail" style="width: 100%">
                <thead>
                    <tr>
                        <th>Account</th>
                        <th>Debit</th>
                        <th>Credit</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
                <tfoot>
                    <tr>
                        <th>Total</th>
                        <th id="sumDebit">0</th>
                        <th id="sumCredit">0</th>
                        <th></th>
                    </tr>
                </tfoot>
            </table>
            <div class="form-control" style="margin-top: 10px;">
                <c:choose>
                    <c:when test="${not empty requestScope.xmlContent}">
                        <input type="button" value="Save" onclick="save()"/>
                    </c:when>
                    <c:otherwise>
                        <input type="button" value="Add" onclick="save()"/>
                    </c:otherwise>
                </c:choose>
                <a href="Accountant?action=listTransaction" class="button" id="btnCancel">Cancel</a>
            </div>
        </div>
    </body>
</html>
